let commodity_options = {}
let price_id = null
let price_show = null
let change_option = null
let inventory_show = '无限'

layui.use(['layer', 'form', 'carousel', 'jquery', 'element'], function () {
  var layer = layui.layer
    , form = layui.form
    , carousel = layui.carousel
    , $ = layui.$

  // 实现放大镜效果
  $("#largePicDiv").mousemove(function (e) {
    $('.mainImg .zoom_pup').css("opacity", 0.3);
    $('.big_pic').css("display", "block");
    let ev = e || event;
    let mouseX = ev.pageX;
    let mouseY = ev.pageY;
    let picLeft = $("#largePic").offset().left;
    let picTop = $("#largePic").offset().top;
    let picWidth = $("#largePic").width();
    let picHeight = $("#largePic").height();
    let xLength = mouseX - picLeft;
    let yLength = mouseY - picTop;
    let qWidth = picWidth / 4;
    let lastQWidth = picWidth - picWidth / 4;
    let qHeight = picHeight / 4;
    let lastQHeight = picHeight - picHeight / 4;
    if (xLength < qWidth) {
      $("#move").css("left", "0px");
    } else {
      if (xLength > lastQWidth) {
        $("#move").css("left", (lastQWidth - qWidth) + "px");
      } else {
        $("#move").css("left", (xLength - qWidth) + "px");
      }
    }
    if (yLength < qHeight) {
      $("#move").css("top", "0px");
    } else {
      if (yLength > lastQHeight) {
        $("#move").css("top", (lastQHeight - qHeight) + "px");
      } else {
        $("#move").css("top", (yLength - qHeight) + "px");
      }
    }
    $("#detailPic > img").css("left", parseInt($("#move").css("left")) * (-800 / picWidth) + "px").css("top", parseInt($("#move").css("top")) * (-800 / picWidth) + "px").css("position", "absolute");
  }).mouseout(function () {
    $('.big_pic').css("display", "none");
    $('.mainImg .zoom_pup').css("opacity", 0);
  })

  // 实现选择展示图片，展示大图
  $(".allImg img").mouseover(function () {
    $(".allImg img").removeClass("current");
    $(this).addClass("current");
    var src = $(this).attr("src");
    $("#largePic").attr("src", src.replace("_x", "_w"));
    $("#detailPic img").attr("src", src.replace("_x", "_b"));
  });

  // 定义函数，根据选项，动态的展示价格和库存
  // 定义函数，根据选项，动态的展示价格和库存
  change_option = function (name, id, price, inventory, options) {
    if (price) { // 价格
      price_show = price
      price_id = id
    }
    if (inventory) { // 库存
      inventory_show = inventory
    }

    $(`#option${id}`).parent().children().css('border', '2px solid white')
    $(`#option${id}`).css('border', '2px solid red')
    commodity_options[name] = {
      'id': id,
      'price': price,
      'inventory': inventory,
      'options': options
    }
    $('.product-price').text('￥' + price_show)
    $('.inventory').text(inventory_show)
    //console.log(commodity_options)
  }
  id = window.location.search.substr(1).match(new RegExp("(^|&)id=([^&]*)(&|$)", "i"))[2];
  // 获取商品购买选项数据
  $.get('/commodity/get_options/', {'id': id}, function (data) {
    console.log(data)
    let options = data.data
    let content = ``
    $.each(options, function (i, option) {

      // 新增，实现价格的自动渲染
      commodity_options[option[0]] = option[1][0]
      if (option[1][0].price) {
        price_show = option[1][0].price
        price_id = option[1][0].id
      }
      if (option[1][0].inventory) {
        inventory_show = option[1][0].inventory
      }

      content += `<li>
                    <span class="product-name">${option[0]}</span>
                    <ul class="options">
                    `
      $.each(option[1], function (x, args) {

        // 实现选项被选中后样式添加
        let cls = ''
        if (x == 0) {
          cls = 'class="pitch"'
        }

        content += `<li ${cls} id="option${args.id}" onclick="change_option('${option[0]}',${args.id},${args.price},${args.inventory},'${args.options}')">`
        if (args.img) {
          content += `<img
                                src="` + args.img + `"
                                alt="` + args.options + `"
                                title="` + args.options + `">`
        } else {
          content += args.options
        }
        content += `</li>`
      })
      content += `</ul>
                </li>`
    })
    // console.log(content)
    $('#option-item').html(content)
    $('.product-price').text('￥' + price_show)
    $('.inventory').text(inventory_show)
  });


  function search() {
    console.log(1)
    window.open(`/commodity/search/?q=${$('#inputKeywords').val()}`, '_blank')
  }

// 点击搜索
  $('#search-btn').click(search)

// 回车搜索
  $('#inputKeywords').keydown(function (event) {
    if (event.keyCode == 13) {
      search();
    }
  })

// 加入购物车
  $('.shopping-car-btn').click(function () {

    // 定义列表存放加入购物车的商品id
    let options_car = []
    $.each(commodity_options, function (i, commodity) {
      //console.log(commodity);
      options_car.push(commodity.id);
    })

    $.ajax({
      type: "POST",
      url: '/shopping_car/',
      headers: {
        'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val()
      },
      data: {
        'id': id,
        'options': JSON.stringify(options_car),
        'number': $('.by-num').val()
      },
      success: function (data) {
        console.log(data);
        layer.msg('添加成功', {icon: 6});
        location.reload();
      }

    });


  })
  // 立即购物
  $('.shopping-btn').click(function () {
    // 构造需要向后台传送的数据
    let subject = $('#product-title').text() + '。|'
    for (let n in commodity_options) {
      subject += `${n}:${commodity_options[n].options}。|`
    }
    console.log(subject); //弗洛伊德厚底板鞋。|颜色分类:玫红色。|尺码:35。|

    $.ajax({
      type: "POST",
      url: '/order/alipay/',
      headers: {
        'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val()
      },
      data: {
        'id': id,
        'option_id': price_id,
        'subject': subject,
        'num': $('.by-num').val(),
      },
      success: function (data) {
        console.log(data.data);
        window.open(data.data)
      }
    })
  })
// console.log(subject);
})